package gov.child.dao.impl;

import gov.child.dao.AbstractDao;
import gov.child.dao.ConsultDao;
import gov.child.dao.exception.*;
import gov.child.entities.po.EConsult;
import gov.child.entities.vo.Page;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * The type Consult dao. --finish
 *
 * @author fzh
 * @since 2017 /9/10
 */
@Repository("consultDao")
public class ConsultDaoImpl extends AbstractDao implements ConsultDao {

    @Override
    public EConsult findById(Integer id) throws EntityQueryException {
        Session session = currentSession();
        return (EConsult) session.createQuery("from EConsult where id = :id order by createTime")
                .setParameter("id", id).uniqueResult();
    }

    @Override
    public List findAll(Page page) throws EntityQueryException {
        Session session = currentSession();
        String hql = "from EConsult order by createTime";
        Query query = session.createQuery(hql);
        return doPaginate(query, page);
    }

    @Override
    public List findByDepartmentId(Integer departmentId, Page page) throws EntityQueryException {
        Session session = currentSession();
        String hql = "from EConsult where deptId = :deptId order by createTime";
        Query query = session.createQuery(hql).setParameter("deptId", departmentId);
        return doPaginate(query, page);
    }

    @Override
    public List findByUserId(Integer userId, Page page) throws EntityQueryException {
        Session session = currentSession();
        String hql = "from EConsult where userId = :uid order by createTime";
        Query query = session.createQuery(hql).setParameter("uid", userId);
        return doPaginate(query, page);
    }

    @Override
    public void save(EConsult consult) throws EntitySaveException {
        currentSession().save(consult);
    }

    @Override
    public void delete(EConsult consult) throws EntityDeleteException {
        currentSession().delete(consult);
    }

    @Override
    public void update(EConsult consult) throws EntityUpdateException {
        // TODO maybe need optimization
        currentSession().update(consult);
    }

    @Override
    public Long total() throws PageInitialException {
        Session session = currentSession();
        String hql = "select count (*) from EConsult ";
        return (Long) session.createQuery(hql).uniqueResult();
    }
}
